<?php

namespace app\admin\controller;

use app\AdminBaseController;


class Admin extends AdminBaseController{


    public function index(){
        if($this->request->isAjax()) {

            $rows = $this->request->param('rows', 10, 'intval');
            $admin = \app\admin\model\Admin::where('id', '>', 0)->order('id desc')->paginate($rows, false);
            foreach ($admin as $item) {
                $item->role_name = \app\admin\model\AdminRole::where('id', '=', $item->role_id)->value('name');
            }
            return json(['total' => $admin->total(), 'rows' => $admin->items()]);
        } else {
            return view();
        }
    }

    //添加时候选则角色
    public function roles(){
        $all = \app\admin\model\AdminRole::where('id','>',0)->select();
        return json(['code'=>200,'message'=>'成功','data'=>$all]);
    }

    public function add(){
        if(!$this->request->isPost()) return json(['code'=>-1,'message'=>'非法请求','data'=>[]]);
        $post = $this->request->post();
        $model = new \app\admin\model\Admin();
        $model->username = $post['username']??'';
        $model->realname = $post['realname']??'';
        $model->email = $post['email']??'';
        $model->mobile = $post['mobile']??'';
        $model->password = md5('qwe123');
        $model->role_id = intval($post['role_id']);
        $model->status = 1;
        $model->create_time = date('Y-m-d H:i:s',time());
        $model->save();
        return json(['code'=>200,'message'=>'ok','data'=>$post]);
    }

    //管理员info
    public function info(){

        $admin = \app\admin\model\Admin::where('id','=',1)->findOrEmpty();
        $admin->roles = ['admin'];
        return json(['code'=>200,'message'=>'成功','data'=>$admin]);
    }

    public function edit(){

    }

    public function del(){
        if(!$this->request->isPost()) return json(['code'=>-1,'message'=>'非法请求','data'=>[]]);
        $id = $this->request->post('id',0,'intval');
        if($id<=0) return json(['code'=>-1,'message'=>'参数错误','data'=>[]]);
        $rt = \app\admin\model\Admin::where('id','=',$id)->delete();
        if($rt){
            return json(['code'=>200,'message'=>'删除成功','data'=>[]]);
        } else {
            return json(['code'=>-1,'message'=>'删除失败','data'=>[]]);
        }
    }


}